#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

cur_dir=$(realpath $(dirname "$0"))

out_dir="${cur_dir}/out/robot"
config_dir="${out_dir}/config"

# check cargo
echo "Check cargo"
cargo --version
if [ $? -ne 0 ]; then
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    source "$HOME/.cargo/env"
fi

# build ferrium
echo "Building x86_64 ferrium"
export FERRIUM_DIR=${cur_dir}/foundation/robot/tools/ferrium
cd ${FERRIUM_DIR} || exit 1
cargo build --release || exit 1
export PATH=${FERRIUM_DIR}/target/release:$PATH

# init ferrium config
echo "initializing ferrium config"
if [ ! -d ${out_dir} ]; then
    mkdir -p ${out_dir}
fi
if [ ! -d ${config_dir} ]; then
    mkdir -p ${config_dir}
fi
cp -rP ${cur_dir}/foundation/robot/tools/ferrium_pkgs/scripts/setup.sh ${out_dir}/
cp -rP ${cur_dir}/foundation/robot/tools/ferrium_pkgs/scripts/setup ${out_dir}/
cp -rP ${cur_dir}/foundation/robot/tools/ferrium_pkgs/config/* ${config_dir}/
cp -rP ${cur_dir}/foundation/robot/tools/ferrium_pkgs/pkgs ${config_dir}/

ferrium init \
    --config-root ${config_dir} \
    --pkgs-root /pkg \
    --shell-configs \
    --local-config ${config_dir} \
    || exit 1

export PKGS_ROOT=/pkg
export CONFIG_ROOT=${config_dir}
cat > ${config_dir}/m-robots-pkgs.toml << EOF
ferrium = { version = "0.1.0", arch = "aarch64" }
musl-ohos = { version = "1.2.3", arch = "aarch64" }
xz = { version = "5.6.3", arch = "aarch64" }
util-linux = { version = "2.40.4", arch = "aarch64" }
coreutils = { version = "9.5", arch = "aarch64" }
tar = { version = "1.35", arch = "aarch64" }
bash = { version = "5.2.37", arch = "aarch64" }
openssl = { version = "3.4.0", arch = "aarch64" }
ncurses = { version = "6.5", arch = "aarch64" }
EOF

ferrium install ${config_dir}/m-robots-pkgs.toml

# generate m-robots
ferrium deploy --root ${out_dir} --single-arch --arch aarch64 ${config_dir}/m-robots-pkgs.toml

# merge aarch64-linux-ohos
cp -rP ${cur_dir}/out/robot/host/usr/lib/aarch64-linux-ohos/lib* ${cur_dir}/out/robot/usr/lib/
rm -rf ${cur_dir}/out/robot/host

cd ${cur_dir}/out || exit 1
tar -zcf release.tar.gz robot || exit 1
